#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<unordered_map>
#include<set>
using namespace std;
const int N = 1e5 + 10;
bool vis[N];
int a[N];
int b[N];
string fristadress;
int n;
unordered_map<int, string> mp;
struct edge {
	int w, v;
}e[N];

int main()
{
	cin >> fristadress >> n;
	int num = stoi(fristadress);
	mp[num] = fristadress;
	int o = 0;
	vector<int> ans[2];
	unordered_map<int, bool> bl;
	while (n--)
	{
		string adress;
		int key;
		string nextadress;
		cin >> adress >> key >> nextadress;
		int num1 = stoi(adress);
		int num2 = stoi(nextadress);
		mp[num1] = adress;
		mp[num2] = nextadress;
		e[num1].w = key;
		e[num1].v = num2;
	}
	while (num != -1)
	{
		if (bl[abs(e[num].w)] == 0)
		{
			ans[0].push_back(num);
			bl[abs(e[num].w)] = 1;
		}
		else {
			ans[1].push_back(num);
		}
		num = e[num].v;
	}
	int key = 0;
	for (auto it : ans[0]) {
		if (!key) {
			printf("%05d %d ", it, e[it].w);
			key = 1;
		}
		else {
			printf("%05d\n%05d %d ", it, it, e[it].w);
		}
	}
	cout << -1 << endl;
	key = 0;
	for (auto it : ans[1]) {
		if (!key) {
			printf("%05d %d ", it, e[it].w);
			key = 1;
		}
		else {
			printf("%05d\n%05d %d ", it, it, e[it].w);
		}
	}
	if (key)
		cout << -1 << endl;
	return 0;
}